package com.citcc.api.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.Base64Helper;
import com.citcc.api.config.JpushConfig;
import com.citcc.common.utils.StringUtils;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class JPushUtil {

    public static final Logger log = LoggerFactory.getLogger(JPushUtil.class);


    //1.发送通知
    public static final String SEND_NOTIFICATION_URL = "https://api.jpush.cn/v3/push";
    //查询单条消息发送状态
    public static final String STATE_NOTIFICATION_URL = "https://report.jpush.cn/v3/status/message";

    /**
     * @param registration_id 注册id
     * @param body            通知内容
     * @param tittle          通知标题
     * @return JSONObject
     * @desc ： 1.调用极光API
     */
    public static JSONObject sendNotification(String registration_id, String tittle, String body, String extrasParam) {

        if (StringUtils.isEmpty(registration_id)){
            Map data =new HashedMap();
            data.put("status","-1");
            data.put("msg","registration_id不能为空!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        if (registration_id.length()<8) {
            Map data = new HashedMap();
            data.put("status", "-1");
            data.put("msg", "registration_id格式不正确!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        if ((!registration_id.contains(","))&&registration_id.length()>25){
            Map data =new HashedMap();
            data.put("status","-1");
            data.put("msg","registration_id格式不正确!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        final Base64Helper encoder = new Base64Helper();
        String base64_auth_string = encoder.encode((JpushConfig.APP_KEY + ":" + JpushConfig.MASTER_SECRET).getBytes());
        String authorization = "Basic " + base64_auth_string;
        System.out.println(authorization);
        String data = generateJson("notification", registration_id, body, tittle, extrasParam).toString();
        System.out.println(data);
        String s = "";
        log.debug("Authorization:" + authorization);
        log.debug("data:" + data);
        try {
            s = SslTest.postBody(SEND_NOTIFICATION_URL, data, authorization);
            log.info("sendNotification返回    "+s);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("sendNotification返回    异常");
        }
        return JSONObject.parseObject(s);
    }

    /**
     * @param registration_id 注册id
     * @param body            通知内容
     * @param tittle          通知标题
     * @return JSONObject
     * @desc ： 1.调用极光API
     */
    public static JSONObject sendMessage(String registration_id, String tittle, String body, String extrasParam) {
        if (StringUtils.isEmpty(registration_id)){
            Map data =new HashedMap();
            data.put("status","-1");
            data.put("msg","registration_id不能为空!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        if (registration_id.length()<8) {
            Map data = new HashedMap();
            data.put("status", "-1");
            data.put("msg", "registration_id格式不正确!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        if ((!registration_id.contains(","))&&registration_id.length()>25){
            Map data =new HashedMap();
            data.put("status","-1");
            data.put("msg","registration_id格式不正确!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        final Base64Helper encoder = new Base64Helper();
        String base64_auth_string = encoder.encode((JpushConfig.APP_KEY + ":" + JpushConfig.MASTER_SECRET).getBytes());
        String authorization = "Basic " + base64_auth_string;
        System.out.println(authorization);
        String data = generateJson("message", registration_id, body, tittle, extrasParam).toString();
        System.out.println(data);
        String s = "";
        log.debug("Authorization:" + authorization);
        log.debug("data:" + data);
        try {
            s = SslTest.postBody(SEND_NOTIFICATION_URL, data, authorization);
            log.info("sendMessage返回    "+s);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("sendMessage返回    异常");
        }
        return JSONObject.parseObject(s);
    }

    /**
     * @param msg_id          消息id
     * @param registration_id 设备id
     * @return JSONObject
     * @desc ： 1.调用极光API
     */
    public static JSONObject getMessageSendResult(Long msg_id, String registration_id, Date date) throws Exception {
        final Base64Helper encoder = new Base64Helper();
        String base64_auth_string = encoder.encode((JpushConfig.APP_KEY + ":" + JpushConfig.MASTER_SECRET).getBytes());
        String authorization = "Basic " + base64_auth_string;
        System.out.println(authorization);
        String data = generateResultJson(msg_id, registration_id, date).toString();
        System.out.println(data);
        log.debug("Authorization:" + authorization);
        log.debug("data:" + data);
        String s = SslTest.postBody(STATE_NOTIFICATION_URL, data, authorization);
        return JSONObject.parseObject(s);
    }
    /**
     * @param registration_id 注册id
     * @param body            通知内容
     * @param tittle          通知标题
     * @return JSONObject
     * @desc ： 1.调用极光API
     */
    public static JSONObject sendCZTNotification(String registration_id, String tittle, String body, String extrasParam) {

        if (StringUtils.isEmpty(registration_id)){
            Map data =new HashedMap();
            data.put("status","-1");
            data.put("msg","registration_id不能为空!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        if (registration_id.length()<8) {
            Map data = new HashedMap();
            data.put("status", "-1");
            data.put("msg", "registration_id格式不正确!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        if ((!registration_id.contains(","))&&registration_id.length()>25){
            Map data =new HashedMap();
            data.put("status","-1");
            data.put("msg","registration_id格式不正确!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        final Base64Helper encoder = new Base64Helper();
        String base64_auth_string = encoder.encode((JpushConfig.CZT_APP_KEY + ":" + JpushConfig.CZT_MASTER_SECRET).getBytes());
        String authorization = "Basic " + base64_auth_string;
        System.out.println(authorization);
        String data = generateJson("notification", registration_id, body, tittle, extrasParam).toString();
        System.out.println(data);
        String s = "";
        log.debug("Authorization:" + authorization);
        log.debug("data:" + data);
        try {
            s = SslTest.postBody(SEND_NOTIFICATION_URL, data, authorization);
            log.info("sendNotification返回    "+s);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("sendNotification返回    异常");
        }
        return JSONObject.parseObject(s);
    }

    /**
     * @param registration_id 注册id
     * @param body            通知内容
     * @param tittle          通知标题
     * @return JSONObject
     * @desc ： 1.调用极光API
     */
    public static JSONObject sendCZTMessage(String registration_id, String tittle, String body, String extrasParam) {
        if (StringUtils.isEmpty(registration_id)){
            Map data =new HashedMap();
            data.put("status","-1");
            data.put("msg","registration_id不能为空!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        if (registration_id.length()<8) {
            Map data = new HashedMap();
            data.put("status", "-1");
            data.put("msg", "registration_id格式不正确!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        if ((!registration_id.contains(","))&&registration_id.length()>25){
            Map data =new HashedMap();
            data.put("status","-1");
            data.put("msg","registration_id格式不正确!");
            JSONObject itemJSONObj = JSONObject.parseObject(JSON.toJSONString(data));
            return itemJSONObj;
        }
        final Base64Helper encoder = new Base64Helper();
        String base64_auth_string = encoder.encode((JpushConfig.CZT_APP_KEY + ":" + JpushConfig.CZT_MASTER_SECRET).getBytes());
        String authorization = "Basic " + base64_auth_string;
        System.out.println(authorization);
        String data = generateJson("message", registration_id, body, tittle, extrasParam).toString();
        System.out.println(data);
        String s = "";
        log.debug("Authorization:" + authorization);
        log.debug("data:" + data);
        try {
            s = SslTest.postBody(SEND_NOTIFICATION_URL, data, authorization);
            log.info("sendMessage返回    "+s);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("sendMessage返回    异常");
        }
        return JSONObject.parseObject(s);
    }

    /**
     * @param msg_id          消息id
     * @param registration_id 设备id
     * @return JSONObject
     * @desc ： 1.调用极光API
     */
    public static JSONObject getCZTMessageSendResult(Long msg_id, String registration_id, Date date) throws Exception {
        final Base64Helper encoder = new Base64Helper();
        String base64_auth_string = encoder.encode((JpushConfig.CZT_APP_KEY + ":" + JpushConfig.CZT_MASTER_SECRET).getBytes());
        String authorization = "Basic " + base64_auth_string;
        System.out.println(authorization);
        String data = generateResultJson(msg_id, registration_id, date).toString();
        System.out.println(data);
        log.debug("Authorization:" + authorization);
        log.debug("data:" + data);
        String s = SslTest.postBody(STATE_NOTIFICATION_URL, data, authorization);
        return JSONObject.parseObject(s);
    }


    /**
     * @param registration_id 注册id  JSON Array
     * @param body            通知内容
     * @param title           通知标题
     * @return JSONObject
     * @desc ：  2.拼装请求json
     */
    private static JSONObject generateJson(String pushType, String registration_id, String body, String title, String extrasParam) {
        JSONArray jsonArray = new JSONArray();
        if (StringUtils.isEmpty(registration_id)) {
            return null;
        } else {
            String[] split = registration_id.split(",");
            List<String> list = Arrays.asList(split);
            jsonArray.addAll(list);
        }
        //总封装
        JSONObject json = new JSONObject();
        //推送目标z指定
        JSONObject audience = getAudience(jsonArray);

        //推送平台指定
        JSONArray platform = getPlatform();

        //通知内容体(消息内容体二选一)
        JSONObject notification = getNotification(body, title, extrasParam);         //3.通知内容
        //消息内容体
        JSONObject message = getMessage(body, title, extrasParam);         //4消息内容
        //获取可选参数(dev)
       JSONObject options = getOptionsDev();
        //获取可选参数(product)
       //JSONObject options = getOptionsProd();

        json.put("platform", platform);
        json.put("audience", audience);
        json.put("options", options);
        if ("message".equals(pushType)) {
            json.put("message", message);
        } else if ("notification".equals(pushType)) {
            json.put("notification", notification);
        }
        return json;

    }

    /**
     * @param registration_id 注册id  JSON Array
     * @param msg_id          消息id
     * @return JSONObject
     * @desc ：  2.拼装请求json
     */
    private static JSONObject generateResultJson(Long msg_id, String registration_id, Date date) {
        JSONArray jsonArray = new JSONArray();
        if (StringUtils.isEmpty(registration_id)) {
            return null;
        } else {
            String[] split = registration_id.split(",");
            List<String> list = Arrays.asList(split);
            jsonArray.addAll(list);
        }
        //总封装
        JSONObject json = new JSONObject();
        json.put("msg_id", msg_id);
        json.put("registration_ids", jsonArray);
        if (date != null) {
            json.put("date", com.citcc.api.utils.DateUtil.formatToYMD(date));
        }

        return json;

    }

    /**
     * 安卓通知封装
     *
     * @param body
     * @param title
     * @return
     */
    private static JSONObject android_Notification(String body, String title, String extrasParam) {
        JSONObject android = new JSONObject();             //3.1 android通知内容
        android.put("alert", body);                      //设置通知内容
        android.put("title", title);                      //设置通知内容
       /* JSONObject android_extras = new JSONObject();//android额外参数
        android_extras.put("type", "infomation");*/
        //android.put("builder_id", 1);//通知栏样式 ID Android SDK 可设置通知栏样式，这里根据样式 ID 来指定该使用哪套样式。
        //android.put("priority", 0);//通知栏展示优先级 默认为 0，范围为 -2～2 ，其他值将会被忽略而采用默认
        //android.put("style", 0);//默认为 0，还有 1，2，3 可选，用来指定选择哪种通知栏样式，其他值无效。有三种可选分别为 bigText=1，Inbox=2，bigPicture=3。
        //android.put("alert_type", 0);//通知提醒方式   可选范围为 -1～7 ，对应 Notification.DEFAULT_ALL = -1 或者 Notification.DEFAULT_SOUND = 1, Notification.DEFAULT_VIBRATE = 2, Notification.DEFAULT_LIGHTS = 4 的任意 “or” 组合。默认按照 -1 处理。
        //android.put("intent", 0);//指定跳转页面   使用 intent 里的 url 指定点击通知栏后跳转的目标页面。
        if (extrasParam != null) {
            JSONObject jsonObject = JSONObject.parseObject(extrasParam);
            android.put("extras", jsonObject);
        }
        return android;
    }

    /**
     * 苹果通知封装
     *
     * @param body
     * @param title
     * @return
     */
    private static JSONObject IOS_Notification(String body, String title, String extrasParam) {
        JSONObject ios = new JSONObject();//3.2 ios通知内容
        ios.put("sound", "default");
        ios.put("badge", "+1");

        //消息体封装
        JSONObject iosNotify = new JSONObject();
        iosNotify.put("title", title);
        iosNotify.put("body", body);

        ios.put("alert", iosNotify);

        /*JSONObject ios_extras = new JSONObject();//ios额外参数
        ios_extras.put("type", "infomation");*/
        if (extrasParam != null) {
            JSONObject jsonObject = JSONObject.parseObject(extrasParam);
            ios.put("extras", jsonObject);
        }
        return ios;
    }

    private static JSONObject getMessage(String body, String title, String extrasParam) {
        JSONObject message = new JSONObject();
        message.put("msg_content", body);
        message.put("title", title);
        // message.put("content_type",);

      /*  JSONObject ios_extras = new JSONObject();//ios额外参数
        ios_extras.put("type", "infomation");*/
        if (extrasParam != null) {
            JSONObject jsonObject = JSONObject.parseObject(extrasParam);
            message.put("extras", jsonObject);
        }
        return message;
    }

    /**
     * 通知封装
     *
     * @param body
     * @param title
     * @return
     */
    private static JSONObject getNotification(String body, String title, String extrasParam) {
        JSONObject notification = new JSONObject();
        JSONObject android = android_Notification(body, title, extrasParam);
        JSONObject ios = IOS_Notification(body, title, extrasParam);
        notification.put("android", android);
        notification.put("ios", ios);
        return notification;
    }

    /**
     * 可选参数
     *
     * @return
     */
    private static JSONObject getOptionsDev() {
        //推送参数
        JSONObject options = new JSONObject();//推送参数
        options.put("apns_production", false);//开发环境false，true 生产环境
        options.put("time_to_live", 3);
        return options;
    }

    /**
     * 可选参数
     *
     * @return
     */
    private static JSONObject getOptionsProd() {
        //推送参数
        JSONObject options = new JSONObject();//推送参数
        options.put("apns_production", true);//开发环境false，true 生产环境
        options.put("time_to_live", 3);
        return options;
    }

    /**
     * 推送平台指定
     *
     * @return
     */
    private static JSONArray getPlatform() {
        //platform必传拼装
        JSONArray platform = new JSONArray();   //1.推送平台设置
        platform.add("android");
        platform.add("ios");
        return platform;
    }

    /**
     * 推送目标指定
     *
     * @return
     */
    private static JSONObject getAudience(JSONArray registration_id) {
        //audience推送设备指定(必填)
        JSONObject audience = new JSONObject();       //2.推送设备指定，即推送目标
        audience.put("registration_id", registration_id);
        return audience;
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap();
        map.put("type", 1000);
        String param = JSONObject.toJSONString(map);
        sendNotification("1104a89792e99e4df33", "充电桩", "开启充电成功","");
    }
    
    
}